<?php
namespace Modules\Frontend\Controllers;

class TradeBuyController extends \Phalcon\Mvc\Controller {
  public function beforeExecuteRoute() {
    \Components\Utils::isClosedFrontent($this);
  }

  public function initialize() {
    $this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');
  }

  public function checkOrderAction() {
    $serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
    if($serviceUser['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
    }

    $findTradeBuy = $this -> trade::getBuyServiceInstance() -> findFirst([
      'conditions' => 'from_user_id = ' . $serviceUser['user'] -> user_id,
      'order' => 'trade_buy_id DESC'
    ]);

    if($findTradeBuy['code'] == 0) {
      if($findTradeBuy['trade_buy'] -> status != 5) {
        if($findTradeBuy['trade_buy'] -> status != 6 && $findTradeBuy['trade_buy'] -> status != 7 || (time() - 604800) < $findTradeBuy['trade_buy'] -> create_time) {
          $serviceMessage = $this -> parameter::getServiceInstance() -> findFirstByKey('TRADE_BUY_EVERY_TIME_MESSAGE');
          return $this -> response -> setJsonContent(['code'=>0,'msg'=>$serviceMessage['model'] -> value]);
        }
      }
    }

    return $this -> response -> setJsonContent(['code'=>0]);
  }

  public function freeze() {
    $service = $this -> trade::getBuyServiceInstance() -> find([
      'conditions' => 'status = 1 AND last_time < ' . (time() - 21600)
    ]);

    if($service['code'] != 0) {
      return false;
    }

    foreach($service['trade_buy'] as $trade_buy) {
      $this -> db -> begin();
      try {
        $serviceUser = $this -> account::getServiceInstance() -> findFirstById($trade_buy -> from_user_id);
        $serviceUser['user'] -> status = 2;
        if(!$serviceUser['user'] -> save())  { throw new \Exception('取消失败'); }

        $findFirstTradeSell = $this -> trade::getSellServiceInstance() -> findFirstById($trade_buy -> trade_sell_id);
        if($findFirstTradeSell['code'] == 0) {
          $findFirstTradeSell['trade_sell'] -> trade_buy_id = 0;
          $findFirstTradeSell['trade_sell'] -> to_user_id = 0;
          $findFirstTradeSell['trade_sell'] -> status = 0;
          if(!$findFirstTradeSell['trade_sell'] -> save())  { throw new \Exception('取消失败'); }
        }

        $trade_buy -> trade_sell_id = 0;
        $trade_buy -> to_user_id = 0;
        $trade_buy -> status = 5;
        if(!$trade_buy -> save())  { throw new \Exception('取消失败'); }

        $this -> db -> commit();
      } catch(\Exception $e) {
        $this -> db -> rollback();

        //return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
      }
    }
  }

  public function indexAction() {
    $serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
    if($serviceUser['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
    }

    $query = $this -> request -> getQuery();
    if(!isset($query['page'])) {
      $query['page'] = 1;
    } else if($query['page'] <= 0)  {
      $query['page'] = 1;
    } else {
      $query['page'] = abs($query['page']);
    }

    if(!isset($query['limit'])) {
      $query['limit'] = 10;
    } else if($query['limit'] <= 0)  {
      $query['limit'] = 10;
    } else {
      $query['limit'] = abs($query['limit']);
    }

    $this -> freeze();

    $service = $this -> trade::getBuyServiceInstance() -> pager([
      'conditions' => 'from_user_id = ' . $serviceUser['user'] -> user_id,
      'order' => 'status ASC,create_time DESC'
    ], $query['limit'], $query['page']);
    if($service['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
    }

    return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'pager' => $service['pager']]);
  }

  public function findFirstByIdAction($id) {
    $serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
    if($serviceUser['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
    }

    $serviceBuy = $this -> trade::getBuyServiceInstance() -> findFirstById($id);
    if($serviceBuy['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$serviceBuy['code'],'msg'=>'进货订单获取失败']);
    }
    /*
    if($serviceBuy['trade_buy'] -> status != 1) {
      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'进货订单已打款']);
    }
    */
    $serviceSell = $this -> trade::getSellServiceInstance() -> findFirstById($serviceBuy['trade_buy'] -> trade_sell_id);
    if($serviceSell['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$serviceSell['code'],'msg'=>'销售订单获取失败']);
    }
    /*
    if($serviceSell['trade_sell'] -> status != 2) {
      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'销售订单已确认打款']);
    }
    */

    $serviceUserSell = $this -> account::getServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> from_user_id);
    if($serviceUserSell['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$serviceUserSell['code'],'msg'=>$serviceUserSell['message']]);
    }
    if($serviceUserSell['user'] -> pid <= 0) {
      $serviceParentUserSell['user'] = [
        'cellphone' => '无推荐人'
      ];
    } else {
      $serviceParentUserSell = $this -> account::getServiceInstance() -> findFirstById($serviceUserSell['user'] -> pid);
      if($serviceParentUserSell['code'] != 0) {
        $serviceParentUserSell['user'] = [
          'cellphone' => '无推荐人'
        ];
      }
    }

    $serviceBankInfo = $this -> account::getBankInfoServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> user_bank_info_id);
    if($serviceBankInfo['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$serviceBankInfo['code'],'msg'=>'银行卡信息获取失败']);
    }

    return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'user_sell' =>$serviceUserSell['user'],'parent_user_sell'=>$serviceParentUserSell['user'], 'trade_buy' => $serviceBuy['trade_buy'],'trade_sell'=>$serviceSell['trade_sell'],'user_bank_info' => $serviceBankInfo['user_bank_info']]);
  }

  public function statusAction($id, $status) {
    $serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
    if($serviceUser['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]); }

    $post = $this -> request -> getPost();
    if(!$this -> security -> checkHash($post['safePassword'], $serviceUser['user'] -> safe_password)) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'安全密码错误']); }

    $serviceBuy = $this -> trade::getBuyServiceInstance() -> findFirstById($id);
    if($serviceBuy['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceBuy['code'],'msg'=>'进货订单获取失败']); }
    if($serviceBuy['trade_buy'] -> status != 1) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'进货订单已打款']); }

    $serviceSell = $this -> trade::getSellServiceInstance() -> findFirstById($serviceBuy['trade_buy'] -> trade_sell_id);
    if($serviceSell['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceSell['code'],'msg'=>'销售订单获取失败']); }
    if($serviceSell['trade_sell'] -> status != 2) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'销售订单已确认打款']); }

    $serviceBuy['trade_buy'] -> last_time = time();
    $serviceSell['trade_sell'] -> last_time = $serviceBuy['trade_buy'] -> last_time;

    switch($status) {
      case 3:
      case '3':
        if(isset($post['imageContent']) && !empty($post['imageContent'])) {
          $saveFileName = date('Y').'/'.date('m').'/'.date('d');
          $path = PUBLIC_PACH . 'u/'.$saveFileName;
          $saveImage = \Components\Utils::base64_image_content($post['imageContent'], $path);
          if($saveImage['code'] != 0) {
            
          } else {
            $saveFileName .= '/'.$saveImage['file_name'];
            $serviceBuy['trade_buy'] -> image = $saveFileName;
          }
        }

        $serviceBuy['trade_buy'] -> status = 3;
        $serviceSell['trade_sell'] -> status = 3;
        break;
    }

    $this -> db -> begin();
    try {
      if(!$serviceBuy['trade_buy'] -> save()) { throw new \Exception('确认失败'); }
      if(!$serviceSell['trade_sell'] -> save()) { throw new \Exception('确认失败'); }

      $this -> db -> commit();
    } catch(\Exception $e) {
      $this -> db -> rollback();

      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
    }

    return $this -> response -> setJsonContent(['code'=>0,'msg'=>'确认成功']);
  }

  public function createAction() {
    $post = $this -> request -> getPost();

    if($post['amount'] <= 0) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量不能少于0']); }

    if(($post['amount'] % 1000) != 0) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量输入有误']); }

    $serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
    if($serviceUser['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]); }

    if(!$this -> security -> checkHash($post['safePassword'], $serviceUser['user'] -> safe_password)) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'安全密码错误']); }

    switch($serviceUser['user'] -> level) {
      case 1:
        if($post['amount'] > 5000) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'输入数量大于指定数量']); }
        break;
      case 2:
        if($post['amount'] > 10000) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'输入数量大于指定数量']); }
        break;
      case 3:
      case 4:
        if($post['amount'] > 20000) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'输入数量大于指定数量']); }
        break;
    }

    $serviceUserWallet = $this -> account::getWalletServiceInstance() -> findFirstById($serviceUser['user'] -> user_id);
    if($serviceUserWallet['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUserWallet['code'],'msg'=>$serviceUserWallet['message']]); }

    if($post['amount'] < 10000) { $priceTrade = 1; }
    else if($post['amount'] >= 10000) { $priceTrade = 2; }
    else { $priceTrade = 0; }
    if($serviceUserWallet['user_wallet'] -> price_trade < $priceTrade) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'交易票不足']); }

    $buyParams = [
      'conditions' => 'from_user_id = ' . $serviceUser['user'] -> user_id,
      'order' => 'trade_buy_id DESC',
      'limit' => 4
    ];
    $findTradeBuyR = $this -> trade::getBuyServiceInstance() -> find($buyParams);
    $findTradeBuyB = $this -> tradeSecond::getBuyServiceInstance() -> find($buyParams);
    if($findTradeBuyR['code'] != 0 && $findTradeBuyB['code'] != 0) {
      $findTradeBuy = $findTradeBuyR;
    } else if($findTradeBuyR['code'] == 0 && $findTradeBuyB['code'] != 0) {
      $findTradeBuy = $findTradeBuyR;
    } else if($findTradeBuyR['code'] != 0 && $findTradeBuyB['code'] == 0) {
      $findTradeBuy = $findTradeBuyB;
    } else {
      $firstTradeBuyR = $findTradeBuyR['trade_buy'] -> getFirst();
      $firstTradeBuyB = $findTradeBuyB['trade_buy'] -> getFirst();
      if($firstTradeBuyR -> loop_number >= $firstTradeBuyB -> loop_number) {
        $findTradeBuy = $findTradeBuyR;
      } else {
        if($firstTradeBuyR -> original_amount > $firstTradeBuyB -> original_amount) {
          $findTradeBuy = $findTradeBuyR;
        } else {
          $findTradeBuy = $findTradeBuyB;
        }
      }

      unset($firstTradeBuyR);
      unset($firstTradeBuyB);
    }
    unset($findTradeBuyR);
    unset($findTradeBuyB);

    $profit = 0;
    $loopNumber = 1;
    $isFirst = 1;
    $currentTime = time();
    if($findTradeBuy['code'] != 0) {
      if($post['amount'] < 2000) {
        return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'首次进单不能少于2000']);
      }
      if($post['amount'] > 5000) {
        return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'首次进单不能大于5000']);
      }

      if($post['amount'] < 5000) {
        $profit = 11;
      } else if($post['amount'] < 10000) {
        $profit = 10;
      } else if($post['amount'] >= 10000) {
        $profit = 13;
      }

      $isFirst = 0;
    } else {
      $firstTradeBuy = $findTradeBuy['trade_buy'] -> getFirst();
      if($firstTradeBuy -> status != 5) {
        if(
          $firstTradeBuy -> status != 6 &&
          $firstTradeBuy -> status != 7 &&
          $firstTradeBuy -> create_time > ($currentTime - 604800)
        ) {
          //return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'请等候上一单匹配完成']);
          $serviceMessage = $this -> parameter::getServiceInstance() -> findFirstByKey('TRADE_BUY_EVERY_TIME_MESSAGE');
          return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$serviceMessage['model'] -> value]);
        }
      }

      if($firstTradeBuy -> original_amount > $post['amount']) {
        return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量不能少于上次的'.$firstTradeBuy -> original_amount]);
      }

      switch($findTradeBuy['trade_buy'] -> count()) {
        case 1:
          if($post['amount'] > 5000) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'二次进单不能大于5000']); }
          break;
        case 2:
          if($post['amount'] > 10000) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'三次进单不能大于10000']); }
          break;
        default:
          if($post['amount'] > 20000) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'进单不能大于20000']); }
          break;
      }

      /*
      if($firstTradeBuy -> original_amount < 5000) {
        if($post['amount'] >= 5000) { $profit = 10; } else { $profit = 16; }
      } else if($firstTradeBuy -> original_amount < 10000) {
        if($post['amount'] >= 10000) { $profit = 8; } else { $profit = 15; }
      } else if($firstTradeBuy -> original_amount >= 10000) { $profit = 13; }
      */
      $loopNumber = $firstTradeBuy -> loop_number + 1;
      if($loopNumber > 6) { $loopNumber = 1; }

      if($loopNumber >= 6) { $profit = 0; }
      else if($post['amount'] >= 10000) { $profit = 13; }
      else if($post['amount'] >= 5000) { $profit = 15; }
      else if($post['amount'] >= 2000) { $profit = 16; }
    }

    $this -> db -> begin();
    try {
      $serviceTrade = $this -> account::getWalletServiceInstance() -> updateDecAmount(['type'=>4,'amount'=>$priceTrade,'user_id'=>$serviceUser['user'] -> user_id]);
      if($serviceTrade['code'] != 0) { throw new \Exception($serviceTrade['message']); }
      //if($serviceTrade['code'] != 0) { throw new \Exception('进货失败'); }

      $createTrade = $this -> trade::getBuyServiceInstance() -> create([
        'trade_sell_id' => 0,
        'from_user_id' => $serviceUser['user'] -> user_id,
        'to_user_id' => 0,
        'profit' => $profit,
        'amount' => $post['amount'],
        'original_amount' => $post['amount'],
        'loop_number' => $loopNumber,
        'create_time' => time(),
        'last_time' => time(),
        'status' => 0,
        'is_first' => $isFirst
      ]);
      if($createTrade['code'] != 0) {
        throw new \Exception($createTrade['message']);
      }

      $this -> db -> commit();
    } catch(\Exception $e) {
      $this -> db -> rollback();

      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
    }

    return $this -> response -> setJsonContent(['code'=>0,'msg'=>'进货成功']);
  }

  public function cancalAction($id) {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		$findFirstTradeBuy = $this -> trade::getBuyServiceInstance() -> findFirst([
			'conditions' => 'trade_buy_id = ' . $id . ' AND from_user_id = ' . $serviceUser['user'] -> user_id
		]);
		if($findFirstTradeBuy['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$findFirstTradeBuy['code'],'msg'=>$findFirstTradeBuy['message']]);
		}
		if($findFirstTradeBuy['trade_buy'] -> status != 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'订单操作错误!']);
		}

		if($findFirstTradeBuy['trade_buy'] -> amount < 10000) {
			$priceTrade = 1;
		} else if($findFirstTradeBuy['trade_buy'] -> amount >= 10000) {
			$priceTrade = 2;
		} else {
			$priceTrade = 0;
		}

		$this -> db -> begin();
		try {
			$serviceTrade = $this -> account::getWalletServiceInstance() -> updateIncAmount(['type'=>4,'amount'=>$priceTrade,'user_id'=>$findFirstTradeBuy['trade_buy'] -> from_user_id]);
			if($serviceTrade['code'] != 0) { throw new \Exception('取消失败'); }

			$findFirstTradeBuy['trade_buy'] -> trade_sell_id = 0;
			$findFirstTradeBuy['trade_buy'] -> to_user_id = 0;
			$findFirstTradeBuy['trade_buy'] -> status = 7;
			$findFirstTradeBuy['trade_buy'] -> last_time = time();
			if(!$findFirstTradeBuy['trade_buy'] -> save())  { throw new \Exception('取消失败'); }

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'取消成功']);
	}
}